package com.codeckz.library_face.controller

import android.R.attr
import android.graphics.Bitmap
import android.graphics.PointF
import android.graphics.Rect
import android.media.FaceDetector
import android.util.Log
import kotlin.math.abs


/**
 *@packageName com.codeckz.library_face.controller
 *@author kzcai
 *@date 2022/1/10
 */
class AndroidFilterFace : BaseFilterFace() {


    override fun checkFace(bitmap: Bitmap, checkArea: Rect): FilterFaceResult {
        val faceBitmap = bitmap.copy(Bitmap.Config.RGB_565, true)
        val mFaceDetector = FaceDetector(faceBitmap.width, faceBitmap.height, 1)
        val mFaces = arrayOfNulls<FaceDetector.Face>(1)
        val value = mFaceDetector.findFaces(faceBitmap, mFaces)
//        Log.d(
//            "AndroidFilterFace",
//            "人脸数量：${value.toString()}\n" +
//                    "图片格式${faceBitmap.config.name}\n图片大小：${faceBitmap.width}x${faceBitmap.height}"
//        )
        faceBitmap.recycle()
        if (value == 0) {
            return FilterFaceResult(false, "未检测到人脸", 0)
        }

        val rectWidth = checkArea.width()
        val min = (0.14 * rectWidth).toInt()
        val max = (0.37 * rectWidth).toInt()

        if (mFaces[0] != null) {
            val face = mFaces[0]!!
            val eyesDistance: Float = mFaces[0]!!.eyesDistance()
            val pointF = PointF()
            face.getMidPoint(pointF)
            val faceBottom = pointF.y + eyesDistance * 3 / 2
            return if (eyesDistance < min) {
                FilterFaceResult(false, "请靠近摄像头", value)

            } else if (eyesDistance > max) {
                FilterFaceResult(false, "请稍微远离摄像头", value)
            } else if (faceBottom > checkArea.bottom || abs(pointF.x - (checkArea.right + checkArea.left) / 2) > 0.2*rectWidth) {
                FilterFaceResult(false, "把脸移入框内", value)
            }
            else {
                FilterFaceResult(true, "识别成功", value)
            }
        }

        return FilterFaceResult(false, "把脸移入框内", value!!)

    }
}